package com.gl.codewar.template;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ProvideJustification {

	public static String justify(String sampleInput) {
		
		String result = "";
		
		String [] words = sampleInput.split(" ");
		Integer lineLength = 0;
		
		List<String> currentLine = new ArrayList<String>();
		
		String currentWord = "";
		
		int i = 0;
		
		while (i < words.length) {
			
			String word = currentWord.equals("") ? words[i] : currentWord;
			Integer spaces = currentLine.size() - 1;
			if (lineLength + word.length() + spaces > 30) {
				
				String [] dots = new String [currentLine.size() - 1];
				for (int j = 0; j < dots.length; j++) {
					dots[j] = "";
				}
				
				Integer diff = 30 - lineLength;
				
				for (int j = 0; j < diff; j++) {
					dots [(j % dots.length)] += ".";
				}
				
				String line = "";
				
				for (int j = 0; j < dots.length; j++) {
					line += currentLine.get(j) + dots[j];
				}
				
				line += currentLine.get(currentLine.size() - 1);
				
				result += line + "\n";
				
				currentLine.clear();
				lineLength = 0;
				currentWord = words[i];
			} else {				
				currentLine.add(word);
				lineLength += word.length();
				currentWord = "";
				i++;
			}
			
			
		}
		
		if (currentLine.size() == 1) {
			result += currentLine.get(0);
		}
		
		// TODO Auto-generated method stub
		return result;
	}

}
